package com.atguigu.gulimall.order.listener;

import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "order.seckill.order.queue")
public class OrderSeckillListener {

    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(SeckillOrderTo seckillOrder, Channel channel, Message message) throws IOException {
        try{
            log.info("准备创建秒杀单的详细信息");
            //库存回滚条件 订单创建中途其他服务出错回滚/或者订单没有支付状态码是4
            //问题，若是订单系统由于机器卡顿，消息延迟，没有将状态改为取消，那么这个订单 库存将永远不会解锁
            //解决方法，订单若是释放了，再次主动发个消息，让库存系统再确认一次解锁库存
            System.out.println("开始关闭订单");
            orderService.createSeckillOrder(seckillOrder);
            //手动调用支付宝的收单功能

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
